package fightplan;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JOptionPane;

import fightplan.business.Tournament;
import fightplan.diag.ModeDialog;
import fightplan.persistence.FilePersistence;

public class ModeControl {

	private static ModeControl instance;
	private LastFiles lastFiles;
	private Tournament tournament;

	private ModeControl() {
		lastFiles = new LastFiles();
	}

	public static ModeControl getInstance() {
		if (instance == null) {
			instance = new ModeControl();
		}
		return instance;
	}

	public void choose() {
		tournament = null;

		final ModeDialog dialog = new ModeDialog(null, true);
		dialog.setLocationRelativeTo(null);
		dialog.jComboBoxFile.removeAllItems();

		if (lastFiles.getFileCount() == 0) {
			dialog.jRadioLast.setEnabled(false);
			dialog.jComboBoxFile.setEnabled(false);
			dialog.jRadioKyu.setSelected(true);
		} else {
			File[] files = lastFiles.getFiles();
			for (int i = 0; i < lastFiles.getFileCount(); i++) {
				dialog.jComboBoxFile.addItem(files[i].getName());
			}
			if (lastFiles.isOld()) {
				dialog.jRadioKyu.setSelected(true);
			} else {
				dialog.jRadioLast.setSelected(true);
			}
		}

		dialog.jButtonOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (dialog.jRadioFuji.isSelected()) {
					tournament = new Tournament(Mode.FUJI2008);
				} else if (dialog.jRadioKyu.isSelected()) {
					tournament = new Tournament(Mode.SKRKYU);
				} else if (dialog.jRadioKyuKinder.isSelected()) {
					tournament = new Tournament(Mode.SKRKYU_KINDER);
				} else if (dialog.jRadioIpponShobu.isSelected()) {
					tournament = new Tournament(Mode.IPPONSHOBU);
				} else if (dialog.jRadioGeneral.isSelected()) {
					tournament = new Tournament(Mode.GENERIC);
				} else {
					File file = lastFiles.getFiles()[dialog.jComboBoxFile.getSelectedIndex()];
					try {
						tournament = FilePersistence.load(file, true);
					} catch (Exception x) {
						x.printStackTrace();
						JOptionPane
								.showMessageDialog(dialog,
										"File kann nicht gelesen. Es ist entweder kein Turnierfile\noder von einer anderen Version geschrieben worden.");
					}
				}

				dialog.setVisible(false);
			}
		});

		dialog.setVisible(true);
	}

	public LastFiles getLastFiles() {
		return lastFiles;
	}

	public Tournament getTournament() {
		return tournament;
	}

}
